﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Beacon.Random
{
    public class NormalDistribution :Distribution
    {
        #region Members

        private double _precomputed;
        private bool _usePrecomputed;
        public double Mu { get { return _mu; } set { _mu = value; Reset(); } }
        public double Sigma { get { return _sigma; } set { _sigma = value; Reset(); } }
        private double _mu;
        private double _sigma;

        #endregion

        #region Constructors

        public NormalDistribution():base(new StandardGenerator())
        {
        }

        public NormalDistribution(Generator g):base(g)
        {
            Mu = 1.0;
            Sigma = 1.0;
        }

        public NormalDistribution(Generator g, double mu, double sigma)
            : base(g)
        {
            Mu = mu;
            Sigma = sigma;
        }
        public NormalDistribution(double mu, double sigma)
            : this(new StandardGenerator(),mu,sigma)
        { 
        }

        #endregion
        
        public override bool Reset()
        {
            _precomputed = 0.0;
            _usePrecomputed = false;
            return base.Reset();
        }

        /// <summary>
        /// This is from Troschuetz.Random Class Library. (stefan@troschuetz.de)
        /// I didn't know the Mathematics basis :)
        /// </summary>
        /// <returns></returns>
        public override double NextDouble()
        {
            if (_usePrecomputed)
            {
                _usePrecomputed = false;
                return _precomputed;
            }
            else
            {
                _usePrecomputed = true;
                
                while (true)
                {
                    double v1 = 2.0 * this.Gtr.NextDouble() - 1.0;
                    double v2 = 2.0 * this.Gtr.NextDouble() - 1.0;
                    double w = v1 * v1 + v2 * v2;

                    if (w <= 1)
                    {
                        double y = Math.Sqrt(-2.0 * Math.Log(w) / w) * Sigma;
                        this._precomputed = v2 * y + Mu;
                        return v1 * y + Mu;
                    }
                }
            }
        }
    }
}
